﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace IronLua.Metadata
{
    internal static class ByteExtensions
    {

        internal static readonly byte[] LuaSignature = new byte[] { (byte)27, (byte)'L', (byte)'u', (byte)'a' };
        internal static readonly byte[] ChunkHeaderTail = new byte[] { (byte)0x19, (byte)0x93, (byte)'\r', (byte)'\n', 0x1a, (byte)'\n' };

        public static string ToAscii(this byte[] bytes)
        {
            return Encoding.ASCII.GetString(bytes);
        }

        public static VarArgFlags ToVarArgFlags(this byte b)
        {
            return (VarArgFlags)b;
        }

        public static Endianness ToEndianness(this byte b)
        {
            if (b == 0)
                return Endianness.BigEndian;

            if (b == 1)
                return Endianness.LittleEndian;

            throw new LuaMetadataException("Endianness flag out of range.");
        }

        public static NumberType ToNumberType(this byte b)
        {
            if (b == 0)
                return NumberType.FloatingPoint;

            if (b == 1)
                return NumberType.Integral;

            throw new LuaMetadataException("Integral flag out of range.");
        }

        public static ConstantTypes ToConstantType(this byte b)
        {
            var ct = (ConstantTypes)b;

            switch (ct)
            {
                case ConstantTypes.Nil:                    
                case ConstantTypes.Boolean:                    
                case ConstantTypes.Number:                    
                case ConstantTypes.String:
                    return ct;

                default:
                    throw new LuaMetadataException("Bad constant.");
            }
        }

        public static byte[] VerifyChunkHeaderTail(this byte[] bytes)
        {
            if (bytes.SequenceEqual(ByteExtensions.ChunkHeaderTail))
                return bytes;

            throw new LuaMetadataException("Bad chunk header.");
        }

        public static byte[] VerifyLuaSignature(this byte[] bytes)
        {
            if (bytes.SequenceEqual(ByteExtensions.LuaSignature))
                return bytes;

            throw new LuaMetadataException("Wrong Lua signature.");
        }

        public static byte VerifyLuaVersion(this byte b)
        {
            byte lua52ver = 0x52;

            if (lua52ver == b)
                return b;

            throw new LuaMetadataException("Version mismatch.");
        }

    }
}
